package bubuntux.jusbscan.core;

import java.io.BufferedReader;
import java.io.File;

import org.apache.commons.lang.StringUtils;

import bubuntux.jusbscan.core.antivirus.ClamAv;
import bubuntux.util.CommandLine;
import bubuntux.util.Unix;

public abstract class Antivirus {

	public static Antivirus load() {
		Antivirus antivirus = null;

		try {
			antivirus = (Antivirus) Class.forName(
					"bubuntux.jusbscan.core.antivirus." + Configs.antivirus)
					.newInstance();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		if (antivirus == null) {
			antivirus = new ClamAv();
		}

		return antivirus;
	}

	private CommandLine cmd = null;

	protected BufferedReader reader = null;
	protected String lastLine = null;
	protected String penultimateLine = null;

	protected Antivirus(String program) {
		super();
		this.cmd = new CommandLine(program);
	}

	protected Antivirus(String program, String... parameters) {
		super();
		this.cmd = new CommandLine(program, parameters);
	}

	public void bufferResult() {
		this.penultimateLine = this.lastLine;
		this.lastLine = Unix.nextLineOf(reader);
	}

	public abstract boolean finish();

	/**
	 * 
	 * @return the las Scanning file
	 */
	public abstract String getActualFile();

	public abstract String getVirusFiles();

	public abstract boolean isNewFile();

	public boolean scan(File dir) {
		boolean start = false;
		this.reader = null;
		if (dir != null && dir.isDirectory()) {
			this.cmd.add(dir.getAbsolutePath());
			this.reader = Unix.execute(this.cmd);
			this.cmd.remove(dir.getAbsolutePath());
			if (this.reader != null) {
				start = true;
			}
		}
		return start;
	}

	public abstract void update();

	protected void addParameter(String param) {
		if (StringUtils.isNotBlank(param) && this.cmd.contains(param) == false) {
			this.cmd.add(param);
		}
	}

	protected void removeParameter(String param) {
		if (this.cmd.indexOf(param) != 0) {
			this.cmd.remove(param);
		}
	}

}
